<template>
    <div class="addEditArticlePageCont">
      <div class='title'>当前位置：文章管理 / {{articleTitle}}</div>
      <div class="addEditArticlePageMian">
        <Form ref="formAddEditArticle" :model="formAddEditArticle" :rules="ruleAddEditArticle" :label-width="110">
          <FormItem label="所属楼盘：" required>
            <Row>
                <Col span="11">
                  <FormItem prop="city" >
                    <Select
                      :label-in-value="false"
                      v-model="formAddEditArticle.city"
                      @on-select="cityNameFun"
                      filterable
                      placeholder="请搜索选择城市"
                      style=" width: 100%;"
                      :remote-method="cityFun">
                      <Option v-for="(item, index) in cityList" :value="item.cityCode" :key="item.cityCode">{{ item.cityName }}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center" >-</Col>
                <Col span="11" >
                  <FormItem prop="realEstate">
                    <Select
                      v-model="formAddEditArticle.realEstate"
                      filterable
                      :disabled="!formAddEditArticle.city"
                      placeholder="请搜索选择关联楼盘"
                      style=" width: 100%;"
                      :remote-method="realEstateFun">
                      <Option v-for="(item, index) in realEstateList" :value="item.buildingId" :key="item.buildingId">{{ item.buildingAlias }}</Option>
                    </Select>
                  </FormItem>
                </Col>
            </Row>
          </FormItem>
          <FormItem label="文章标题：" prop="articleTitle">
            <Input :maxlength='50' v-model="formAddEditArticle.articleTitle" placeholder="请输入文章标题"></Input>
          </FormItem>
          <FormItem label="文章标签：" prop="articleTags">
              <Select v-model="formAddEditArticle.articleTags" placeholder="请选择文章标签" filterable style=" width: 100%;">
                <Option v-for="(item, index) in articleTagsList" :value="item.labelId" :key="index">{{ item.ztLabelType }}</Option>
              </Select>
          </FormItem>
          <FormItem label="正文：" required>
            <div id="editor"></div>
            <p v-show="editorContents" class="editorContentsError">请输入正文</p>
          </FormItem>
          <FormItem label="封面图：" class="FormItemUpload" required>
            <div class="demo-upload-list" v-for="(item, index) in formAddEditArticle.fileList" :key="index">
              <img :src="item.url">
              <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline" @click="handleRemove(index)"></Icon>
              </div>
            </div>
            <Upload
              ref="upload"
              v-if="formAddEditArticle.fileList.length > 0 ? false : true"
              :show-upload-list="false"
              :data="uploadData"
              :before-upload="handleBeforeUpload"
              name="multipartFile"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
              :format="['jpg','png']"
              :max-size="2048"
              type="drag"
              :on-exceeded-size="handleMaxSize"
              :on-format-error="handleFormatError"
              :action="uploadImageUrl"
              style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
            </Upload>
            <span class="imageSize" v-if="formAddEditArticle.fileList.length > 0 ? false : true">建议尺寸 750*422 大小在1M内</span>
            <p v-show="ImageContents" class="editorContentsError">请选择上传封面图</p>
          </FormItem>
          <div class="footer">
              <Button type="primary" :loading="buttonLoading" @click="addEditArticleSubmit('formAddEditArticle')">{{$route.query.type == 'add' ? '提交审核' : '确定'}}</Button>
              <Button @click="addEditArticleReset('formAddEditArticle')" style="margin-left: 8px">取消</Button>
          </div>
        </Form>
      </div>
      <!-- 图片放大 -->
      <Modal title="图片预览" v-model="imageVisible" :footerHide="true">
          <img :src="previewAddress" style="width: 100%">
      </Modal>
    </div>
</template>
<script>
  import tool from "@/common/tool.js"
  import secret from "@/common/secret.js"
  import { cityBaseList, buildingList, articleCreate, articleUpdate, articleGet, articleNote } from "@/api/materialManagement.js";
  import {unloadImageAll} from "@/api/building";
  import configs from "@/common/config"

  console.log(unloadImageAll)
 export default {
    components: {

    },
    data() {
      return {
      	previewAddress: '',
        uploadData: {
          appName: 'M-Web',
          appVersion: '1.2.2',
          title: new Date().getTime()
        },
        uploadHeaders: {'token': tool.getToken()},
        uploadImageUrl: unloadImageAll,
        editorContents: false,
        ImageContents: false,
        imageVisible: false,
        articleTitle: '',
        cityList: [],
        realEstateList: [],
        articleTagsList: [],
        formAddEditArticle: {
          city: '',
          cityName: '',
          realEstate: '',
          articleTitle: '',
          articleTags: '',
          fileList: []
        },
        ruleAddEditArticle: {
          city: [
            { required: true, message: '请选择城市', trigger: 'change' }
          ],
          realEstate: [
            { required: true, message: '请选择楼盘', trigger: 'change' }
          ],
          articleTitle: [
            { required: true, message: '请输入文章标题', trigger: 'blur' },
            { max: 50, message: '不可超过50位', trigger: 'blur' }
          ],
          articleTags: [
            { required: true, message: '请选择文章标签', trigger: 'change' }
          ]
        },
        editor: null,
        buttonLoading:false
      }
    },
    methods: {
      cityNameFun(val) {
        this.formAddEditArticle.cityName = val.label
      },
      //设置ueditor编辑器
      setUeditor() {
          var that = this;
          that.editor = window.UE.getEditor('editor', {
              //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
              toolbars: [
                  ['fullscreen', 'source', '|', 'undo', 'redo', '|',
                      'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript',
                      'subscript', 'removeformat',
                      'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor',
                      'backcolor', 'insertorderedlist',
                      'insertunorderedlist', 'selectall', 'cleardoc', '|',
                      'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                      'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                      'directionalityltr', 'directionalityrtl', 'indent', '|',
                      'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                      'touppercase', 'tolowercase', '|',
                      'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter',
                      '|',
                      'simpleupload', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment',
                      'map', 'pagebreak', 'template',
                      'background', '|',
                      'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells',
                      'splittorows', 'splittocols', 'charts',
                      'buildingcard'
                  ]
              ],
              //             		//图片测试地址
              //             		serverUrl: '_UHOST_baiduUeditor/ueditor/jsp/controller.jsp',
              //             		//视频上传api
              videoApi: process.env.VUE_APP_API_URL, //'_API_api/v1/plat/article/uploadUeditorVedioFile',
              //             		//图片上传地址
              simpleImgUrl: process.env.VUE_APP_API_URL, // + '?fileName=' + fileNames,
              // simpleImgUrl: __COMMONAPI__+Api.systemManage.article.uploadArticle,//'_API_api/v1/plat/article/uploadUeditorArticle',
              //关闭字数统计
              wordCount: false,
              //关闭elementPath
              elementPathEnabled: false,
              //默认的编辑区域高度
              initialFrameHeight: 300,
              //默认的编辑区域宽度
              initialFrameWidth: 688,
              //是否自动增长
              autoHeightEnabled: false,
              // 层级
              zIndex: 899
          });
      },
      // 文章管理
      addEditArticleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (!this.editor.hasContents()) {
            this.editorContents = true
            return false;
          } else {
            this.editorContents = false
          }
          if (this.formAddEditArticle.fileList.length == 0) {
            this.ImageContents = true
            return false;
          } else {
            this.ImageContents = false
          }
          if (this.$route.query.type == 'add'){
            let params =  {
              cityName: this.formAddEditArticle.cityName,
              cityCode: this.formAddEditArticle.city,
              buildingId: this.formAddEditArticle.realEstate,
              articleTitle: this.formAddEditArticle.articleTitle,
              labelIdList: this.formAddEditArticle.articleTags,
              articleContent: this.editor.getContent(),
              articleImage: this.formAddEditArticle.fileList[0].url
            }
            this.buttonLoading = true;
            articleCreate(params).then(res=>{
              this.$Message.success('新增文章成功!');
              this.$router.go(-1);
            }).catch(err=>{
              this.$Message.error(err);
               this.buttonLoading = false;
            })
          } else {
            let params =  {
              articleId: this.$route.query.articleId,
              cityName: this.formAddEditArticle.cityName,
              cityCode: this.formAddEditArticle.city,
              buildingId: this.formAddEditArticle.realEstate,
              articleTitle: this.formAddEditArticle.articleTitle,
              labelIdList: this.formAddEditArticle.articleTags,
              articleContent: this.editor.getContent(),
              articleImage: this.formAddEditArticle.fileList[0].url
            }
            articleUpdate(params).then(res=>{
              this.$Message.success('修改文章成功!');
              this.$router.go(-1);
            }).catch(err=>{
              this.$Message.error(err)
            })
          }
          if (valid) {
            this.$Message.success('Success!');
          }
        })
      },
      // form 表单
      addEditArticleReset (name) {
      	this.$router.go(-1);
      },
      // 搜索楼盘
      realEstateFun(value) {
        if(!value) {
          this.realEstateList = []
        } else {
          buildingList({buildingAlias: value, cityCode: this.formAddEditArticle.city}).then(res=>{
            if (res) {
              this.realEstateList = res.list
            }
          }).catch(err=>{
            this.$Message.error(err)
          })
        }
      },
      // 搜索城市
      cityFun(value) {
        if(!value) {
          this.cityList = []
        } else {
          cityBaseList({level: 3, cityName: value}).then(res=>{
            if (res) {
              this.cityList = res.list
            }
          }).catch(err=>{
            this.$Message.error(err)
          })
        }
      },
      handleBeforeUpload(val){
        console.log(val,'请求参数');
      },
      // 上传成功回调
      handleSuccess(res, file) {
        if (res.code == '200') {
          this.ImageContents = false
          let dataJson = JSON.parse(secret.Decrypt(res.data));
          let params = {
              url: dataJson.imageURL,
              name: new Date().getTime()
            }
          this.formAddEditArticle.fileList.push(params)
        } else {
          console.log('上传出错');
        }
      },
      handleMaxSize (file) {
        this.$Message.warning('单个图片不能超过2MB');
      },
      // 文件格式验证失败
      handleFormatError (file) {
        this.$Message.warning('图片格式只支持jpg,png格式！');
      },
      handleView(val) {
      	this.previewAddress = val
        this.imageVisible = true
      },
      handleRemove(index) {
        this.formAddEditArticle.fileList.splice(index, 1)
      },
      //获取文章标签列表
      getNotes(){
        articleNote({projectSummaryFlag:2}).then(res=>{
          console.log("标签列表",res);
          this.articleTagsList = res.list || [];
        })
      }

    },
    computed: {

    },
    created() {
      // 为编辑器添加接口地址
      window.localStorage.setItem("simpleImgUrl", process.env.VUE_APP_API_URL || configs.baseURL.target)
      //获取文章标签
      this.getNotes()
      // 判断新增与编辑
      if (this.$route.query.type == 'add') {
        this.articleTitle = '新增文章'
        document.title = '新增文章'
      } else if (this.$route.query.type == 'edit') {
        this.articleTitle = '编辑文章'
        document.title = '编辑文章'
        articleGet({articleId: this.$route.query.articleId}).then(res=>{
          if(res) {
            this.cityList = [{cityName: res.cityName, cityCode: res.cityCode}]
            this.realEstateList = [{buildingAlias: res.buildingAlias, buildingId: res.buildingId}]
            this.formAddEditArticle.cityName = res.cityName
            this.formAddEditArticle.city = res.cityCode
            this.formAddEditArticle.realEstate = res.buildingId
            this.formAddEditArticle.articleTitle = res.articleTitle
            this.formAddEditArticle.articleTags = res.labelId
            this.formAddEditArticle.fileList = [{url: res.articleImage}]
            this.$nextTick(() => {
              this.editor.ready(() => {
                this.editor.setContent(res.articleContent);
              });
            })
          }
        }).catch(err=>{
          this.$Message.error(err)
        })
      }
    },
    destroyed() {
      this.editor.destroy();
    },
    mounted() {
      this.$nextTick(function(){
        this.setUeditor();
        let that = this
        this.editor.addListener("contentChange",function(){
          if (!that.editor.hasContents()) {
            that.editorContents = true
          } else {
            that.editorContents = false
          }
        });
      })
    },
    watch: {
      // "$route"(to, from) {
      //   if(to.path == "######") {
      //     this.initData();
      //   }
      // }
    },
  }
</script>
<style lang="scss" scoped>
  .addEditArticlePageCont{
    .editorContentsError{
      color: #ed4014;
      font-size: 14px;
      position: absolute;
      left: 0;
      bottom: -26px;
    }
    .title{
        background-color: #f5f5f5;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        padding: 0 14px 10px;
    }
    .addEditArticlePageMian{
      margin-top: 16px;
      width: 800px;
    }
  }
  .footer{
    text-align: center;
    button{
      width: 90px;
      margin: 0 10px;
    }
  }
  // 上传
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .FormItemUpload .ivu-form-item-content{
    display: flex;
  }
  .imageSize{
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
  }
</style>
